import  ast
import glob
import os
import math
import numpy as np
import matplotlib
import pandas as pd
import matplotlib.pyplot as plt
import pandas as pd
import pytz
import matplotlib.dates as mdates
# 设置全局字体


matplotlib.rcParams['font.sans-serif'] = ['SimHei']  # 黑体字
matplotlib.rcParams['axes.unicode_minus'] = False    # 解决负号显示问题
timezone = pytz.timezone('Asia/Shanghai')
def hr_img(save_dir,test,stage,ecghr,ppghr,step):

    # 创建图形
    plt.figure(figsize=(10, 6))
    timestamps1 = [pd.to_datetime(ts, unit='ms', utc=True).tz_convert(timezone) for ts, _ in ecghr]
    values1 = [item[1] for item in ecghr]
    timestamps2 = [pd.to_datetime(ts, unit='ms', utc=True).tz_convert(timezone) for ts, _ in ppghr]
    values2 = [item[1] for item in ppghr]

    # 创建图形
    plt.figure(figsize=(10, 6))

    # 绘制两个RR间期序列




    # print(timestamps1)
    # print(timestamps2)
    plt.plot(timestamps1, values1, linestyle='-', color='r', label='ECG_HR' + ',' + str(len(ecghr)))
    plt.plot(timestamps2, values2, linestyle='-', color='b', label='PPG_HR' + ',' + str(len(ppghr)))
    # 添加标题和标签
    title=str(test)+"-"+str(stage[0])+"-"+str(stage[7])
    plt.title(title)
    plt.xlabel('HR个数')
    plt.ylabel('HR(/min)')

    # 添加图例
    plt.legend()
    save_dir=save_dir+'\\'+str(step)+'s\\img_hr'+'\\'
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    plt.savefig(save_dir+title+'.png')
    # 显示图形
    plt.show()

def rpe_img(save_dir,test,stage,xlrpe,slrpe,step):




    # 创建图形
    plt.figure(figsize=(10, 6))

    # 绘制两个RR间期序列
    plt.plot(xlrpe, linestyle='-', color='b', label='心理rpe')
    plt.plot(slrpe, linestyle='-', color='r', label='生理rpe')

    # 添加标题和标签
    title=str(test)+"-"+stage
    plt.title(title)
    plt.ylabel('量表')
    plt.xlabel('阶段')

    # 添加图例
    plt.legend()
    save_dir=save_dir+'\\'+str(step)+'s\\img_rpe'+'\\'
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    plt.savefig(save_dir+title+'.png')
    # 显示图形
    plt.show()



def ppg_ecg_img(save_dir,test,stage,ppg_stage,ecg_stage,step):
    # timestamps1 = [pd.to_datetime(ts, unit='ms', utc=True).tz_convert(timezone) for ts, _ in ecg_stage]
    # values1 = [item[1] for item in ecg_stage]
    # timestamps2 = [pd.to_datetime(ts, unit='ms', utc=True).tz_convert(timezone) for ts, _ in ppg_stage]
    # values2 = [item[1] for item in ppg_stage]
    #
    #
    #
    #
    # plt.figure(figsize=(10, 6))
    #
    # # 绘制两个RR间期序列
    #
    # plt.plot(timestamps1, values1, linestyle='-', color='r', label='ECG_signal' + ',' + str(len(ecg_stage)))
    # plt.plot(timestamps2, values2, linestyle='-', color='b', label='PPG_signal' + ',' + str(len(ppg_stage)))
    # # plt.plot(timestamps2, smoothed_values2, linestyle='-', color='g', label='PPG_RR优化' + ',' + str(len(smoothed_values2)))
    # # 添加标题和标签
    # title = str(test) + "-" + str(stage[0]) + "-" + str(stage[7])
    # plt.title(title)
    # plt.xlabel('时间戳')
    # plt.ylabel('rri')
    # plt.title(title)
    #
    # # 添加图例
    # plt.legend()
    # save_dir = save_dir + '\\' + str(step) + 's\\img_ppg-ecg' + '\\'
    # if not os.path.exists(save_dir):
    #     os.makedirs(save_dir)
    # plt.savefig(save_dir + title + '.png')
    # # 显示图形
    # plt.show()
    import matplotlib.pyplot as plt
    import pandas as pd
    import os
    import matplotlib.pyplot as plt
    import pandas as pd
    import os
    from pandas.plotting import register_matplotlib_converters

    # 注册时间序列转换器
    register_matplotlib_converters()

    # 其余绘图代码...

    # Assuming ecg_stage and ppg_stage are defined, as well as timezone, test, stage, and save_dir.

    # Convert timestamps and extract values
    timestamps1 = [pd.to_datetime(ts, unit='ms', utc=True).tz_convert(timezone) for ts, _ in ecg_stage]
    values1 = [item[1] for item in ecg_stage]
    timestamps2 = [pd.to_datetime(ts, unit='ms', utc=True).tz_convert(timezone) for ts, _ in ppg_stage]
    values2 = [item[1] for item in ppg_stage]

    # Create subplots
    fig, axs = plt.subplots(2, 1, figsize=(100, 50))

    # Plot ECG signal
    axs[0].plot(timestamps1, values1, linestyle='-', color='r', label='ECG_signal, {}'.format(len(ecg_stage)))
    axs[0].set_title('ECG Signal: {} - {} - {}'.format(test, stage[0], stage[7]))
    axs[0].set_xlabel('时间戳')
    axs[0].set_ylabel('rri')
    axs[0].legend()

    # Plot PPG signal
    axs[1].plot(timestamps2, values2, linestyle='-', color='b', label='PPG_signal, {}'.format(len(ppg_stage)))
    axs[1].set_title('PPG Signal: {} - {} - {}'.format(test, stage[0], stage[7]))
    axs[1].set_xlabel('时间戳')
    axs[1].set_ylabel('rri')
    axs[1].legend()

    # Create save directory if it doesn't exist
    save_dir = os.path.join(save_dir, '{}s'.format(step), 'img_ppg-ecg')
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    # Save the figure
    plt.tight_layout()
    plt.savefig(os.path.join(save_dir, '{}_{}_{}.png'.format(test, stage[0], stage[7])))

    # Show the figure
    plt.show()


def rr_img(save_dir,test,stage,ecgrr,ppgrr,step):
    def moving_average(data, window_size):
        series = pd.Series(data)
        return series.rolling(window=window_size, min_periods=1,center=True).mean().tolist()

    timestamps1 = [pd.to_datetime(ts, unit='ms', utc=True).tz_convert(timezone) for ts, _ in ecgrr]
    values1 = [item[1] for item in ecgrr]
    timestamps2 = [pd.to_datetime(ts, unit='ms', utc=True).tz_convert(timezone) for ts, _ in ppgrr]
    values2 = [item[1] for item in ppgrr]
    window_size=5
    smoothed_values2 = moving_average(values2, window_size)
    # 创建图形

    # A_optimized = improve_rr_accuracy(values2, values1)
    # plot_comparison(values2, values1, A_optimized)
    plt.figure(figsize=(10, 6))

    # 绘制两个RR间期序列

    plt.plot(timestamps1, values1 , linestyle='-', color='r', label='ECG_RR'+','+str(len(ecgrr)))
    plt.plot(timestamps2, values2 , linestyle='-', color='b', label='PPG_RR'+','+str(len(ppgrr)))
    # plt.plot(timestamps2, smoothed_values2, linestyle='-', color='g', label='PPG_RR优化' + ',' + str(len(smoothed_values2)))
    # 添加标题和标签
    title=str(test)+"-"+str(stage[0])+"-"+str(stage[7])
    plt.title(title)
    plt.xlabel('时间戳')
    plt.ylabel('rri')
    plt.title(title)

    # 添加图例
    plt.legend()
    save_dir=save_dir+'\\'+str(step)+'s\\img_rr'+'\\'
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    plt.savefig(save_dir+title+'.png')
    # 显示图形
    plt.show()


def hrv(ecgrr,ppgrr):
    ecgrr=[rr[1] for rr in ecgrr]
    ppgrr=[rr[1] for rr in ppgrr]
    ecgrrsdnn = np.std(ecgrr, ddof=0)
    ppgrrsdnn = np.std(ppgrr, ddof=0)
    ecgrrrmssd = np.sqrt(np.mean(np.diff(ecgrr) ** 2))
    ppgrrrmssd = np.sqrt(np.mean(np.diff(ppgrr) ** 2))


    return ecgrrsdnn,ppgrrsdnn,ecgrrrmssd,ppgrrrmssd
def hrv_img(save_dir,test,list,slrpe,xlrpe,step):
    ecgrrsdnn, ppgrrsdnn, ecgrrrmssd, ppgrrrmssd=[sub[0] for sub in list],[sub[1] for sub in list],[sub[2] for sub in list],[sub[3] for sub in list]
    x = [x for x in range(1,len(ecgrrrmssd)+1)]
    # print(x)
    y1 = ecgrrsdnn
    y2 = ppgrrsdnn
    y3 = ecgrrrmssd
    y4 = ppgrrrmssd
    y5 =slrpe
    y6=xlrpe

    # print(xlrpe,slrpe)
    fig, axs = plt.subplots(3, 1, figsize=(10, 12))

    # 第一个合并子图（ecgrrsdnn 和 ecgrrrmssd）
    ax1 = axs[0]
    ax1.plot(x, ecgrrsdnn, 'r', label='ecgrrsdnn')
    ax1.set_title('ecgrrsdnn and ppgrrsdnn')
    ax1.set_xlabel('阶段')
    ax1.set_ylabel('ecgrrsdnn', color='r')
    ax1.tick_params(axis='y', labelcolor='r')
    ax1.set_xticks(np.arange(1, len(x) + 1, 1))  # 你可以调整刻度间隔
    ax1.grid(True)

    ax2 = ax1.twinx()  # 创建共享x轴的第二个y轴
    ax2.plot(x, ppgrrsdnn, 'b', label='ppgrrsdnn')
    ax2.set_ylabel('ecgrrrmssd', color='b')
    ax2.tick_params(axis='y', labelcolor='b')

    # 第二个合并子图（ppgrrsdnn 和 ppgrrrmssd）
    ax3 = axs[1]
    ax3.plot(x, ecgrrrmssd, 'r', label='ppgrrsdnn')
    ax3.set_title('ecgrrrmssd and ppgrrrmssd')
    ax3.set_xlabel('阶段')
    ax3.set_ylabel('ecgrrrmssd', color='r')
    ax3.tick_params(axis='y', labelcolor='r')
    ax3.set_xticks(np.arange(1, len(x) + 1, 1))  # 你可以调整刻度间隔
    ax3.grid(True)

    ax4 = ax3.twinx()  # 创建共享x轴的第二个y轴
    ax4.plot(x, ppgrrrmssd, 'b', label='ppgrrrmssd')
    ax4.set_ylabel('ppgrrrmssd', color='b')
    ax4.tick_params(axis='y', labelcolor='b')

    # 第三个合并子图（xlrpe 和 slrpe）
    ax5 = axs[2]
    ax5.plot(x, xlrpe, 'y', label='心理rpe')
    ax5.set_title('心理rpe and 生理rpe')
    ax5.set_xlabel('阶段')
    ax5.set_ylabel('心理rpe', color='y')
    ax5.tick_params(axis='y', labelcolor='y')
    ax5.set_xticks(np.arange(1, len(x) + 1, 1))  # 你可以调整刻度间隔
    ax5.grid(True)

    ax6 = ax5.twinx()  # 创建共享x轴的第二个y轴
    ax6.plot(x, slrpe, 'c', label='生理rpe')
    ax6.set_ylabel('生理rpe', color='c')
    ax6.tick_params(axis='y', labelcolor='c')

    # 调整子图之间的间距
    plt.tight_layout()
    save_dir=save_dir+'\\'+str(step)+'s\\img_hrv'+'\\'
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    plt.savefig(save_dir+test+ 'hrv对比' + '.png')
    # 显示图形
    plt.show()

    plt.legend()

    print(ecgrrsdnn, ppgrrsdnn, ecgrrrmssd, ppgrrrmssd)


def rr_boxpolt(csv_dir, save_dir,step):
    path = csv_dir  # 修改为你的目录路径

    # 获取所有CSV文件的路径
    csv_files = glob.glob(os.path.join(path, '*.csv'))

    # 读取所有CSV文件并存储为DataFrame的列表
    dfs = [pd.read_csv(file) for file in csv_files]

    # 如果需要将所有DataFrame合并成一个大的DataFrame
    combined_df = pd.concat(dfs, ignore_index=True, sort=True)

    def extract_third_element(s):
        # 将字符串形式的列表转换为实际的列表
        try:
            lst = ast.literal_eval(s)
            # 返回第三个元素，如果列表长度足够
            return lst[2] if len(lst) > 2 else None
        except (ValueError, SyntaxError):
            # 如果字符串不是有效的列表，返回 None
            return None

    # 打印合并后的DataFrame的前几行
    rest = combined_df[combined_df['name'] == 'rest']

    warmup = combined_df[combined_df['name'] == 'warmup']
    running = combined_df[combined_df['name'] == 'running']
    stand = combined_df[combined_df['name'] == 'stand']
    run_rest = combined_df[combined_df['name'] == 'run_rest']

    cols_to_process = ['nn50个数', 'nn50占比', 'rr个数', 'sd1', 'sd2', '中位数', '均值', '差值的均方根（RMSSD）']
    data = []
    runingdata = []
    # print(combined_df.columns)
    # 应用函数到这些列，并添加新的列来保存结果
    for col in cols_to_process:
        rest[col] = rest[col].apply(extract_third_element)


        data.append(rest[col].dropna().tolist())
    for col in cols_to_process:
        running[col] = running[col].apply(extract_third_element)


        runingdata.append(running[col].dropna().tolist())

    # 生成示例数据



    # 将数据组合成一个列表

    # 创建一个 1x2 的子图布局
    fig, axs = plt.subplots(1, 2, figsize=(12, 6))

    # 第一个箱线图
    axs[0].boxplot(data, labels=cols_to_process)
    axs[0].set_title('rr前后截断' + str(step) + 's-rest阶段分析')
    axs[0].set_ylabel('差值百分比%')

    # 第二个箱线图
    axs[1].boxplot(runingdata, labels=cols_to_process)
    axs[1].set_title('rr前后截断' + str(step) + 's-running阶段分析')
    axs[1].set_ylabel('差值百分比%')

    # 调整布局，使图形不重叠
    plt.tight_layout()

    # 保存合并的图像
    plt.savefig(save_dir + '\\' + str(step) + 's-rr.png')

    # 显示图像
    plt.show()

def hr_boxpolt(csv_dir,save_dir,step):

    path = csv_dir  # 修改为你的目录路径

    # 获取所有CSV文件的路径
    csv_files = glob.glob(os.path.join(path, '*.csv'))

    # 读取所有CSV文件并存储为DataFrame的列表
    dfs = [pd.read_csv(file) for file in csv_files]

    # 如果需要将所有DataFrame合并成一个大的DataFrame
    combined_df = pd.concat(dfs, ignore_index=True,sort=True)


    def extract_third_element(s):
        # 将字符串形式的列表转换为实际的列表
        try:
            lst = ast.literal_eval(s)
            # 返回第三个元素，如果列表长度足够
            return lst[2] if len(lst) > 2 else None
        except (ValueError, SyntaxError):
            # 如果字符串不是有效的列表，返回 None
            return None
    # 打印合并后的DataFrame的前几行
    rest= combined_df [combined_df ['name'] == 'rest']

    warmup= combined_df [combined_df ['name'] == 'warmup']
    running= combined_df [combined_df ['name'] == 'running']
    stand= combined_df [combined_df ['name'] == 'stand']
    run_rest= combined_df [combined_df ['name'] == 'run_rest']

    cols_to_process = ['hr个数', '中位数', '均值','标准差']
    data=[]
    runingdata=[]


    # 应用函数到这些列，并添加新的列来保存结果
    for col in cols_to_process:
        rest[col]=rest[col].apply(extract_third_element)


        data.append(rest[col].dropna().tolist())

    for col in cols_to_process:
        running[col]=running[col].apply(extract_third_element)


        runingdata.append(running[col].dropna().tolist())


    # 生成示例数据



    # 将数据组合成一个列表

    # 创建一个 1x2 的子图布局
    fig, axs = plt.subplots(1, 2, figsize=(12, 6))

    # 第一个箱线图
    axs[0].boxplot(data, labels=cols_to_process)
    axs[0].set_title('hr前后截断' + str(step) + 's-rest阶段分析')
    axs[0].set_ylabel('差值百分比%')

    # 第二个箱线图
    axs[1].boxplot(runingdata, labels=cols_to_process)
    axs[1].set_title('hr前后截断' + str(step) + 's-running阶段分析')
    axs[1].set_ylabel('差值百分比%')

    # 调整布局，使图形不重叠
    plt.tight_layout()

    # 保存合并的图像
    plt.savefig(save_dir + '\\' + str(step) + 's-hr.png')

    # 显示图像
    plt.show()